package org.android.kumoh_ing;


import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public  class StartActivity extends Activity{
	private Button mBtnWrite, groupplus, setting;////////////////////////////////////////
	private EditText mInText;
	FeedListView feedList;
	FeedListAdapter feedAdapter;

//	FileOutputStream fos;
//	FileInputStream fis;
	public String dataCount = "";
	public String curCount = "";
	static public String loc ="";
	String m_id; 
	LocationDBTransfer locationTransfer;
//	private String Info = null;
//	private String groupcount = "";
	//FeedInputThread thread;
//	private String grouplist ="";
	OtherDBTransfer otherTransfer ;
	static public Double latitude ;
	static public Double longitude ;
	private LocationDBTransfer locDBTrans ;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start);
		mBtnWrite = (Button) findViewById(R.id.button2);
		mInText = (EditText) findViewById(R.id.editText1);
		groupplus = (Button) findViewById(R.id.groupplus);
		setting = (Button) findViewById(R.id.button3);
		locationTransfer = new LocationDBTransfer();
		otherTransfer = new OtherDBTransfer();
		m_id = Kumoh_ingActivity.getAppPreferences(this, "facebook_myid" );
		locDBTrans = new LocationDBTransfer();
//		thread = new FeedInputThread();
//		thread.start();
		
		
		setting.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent settingintent = new Intent(getApplicationContext(), SettingActivity.class);
				settingintent.putExtra("my_id", m_id);
				startActivity(settingintent);
			}
		});
		
		mBtnWrite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String statusText = mInText.getText().toString();
				if (statusText.length() < 1) {
					Toast.makeText(getApplicationContext(), "입력 하세요.", 1000).show();
					return;
				}
				updateStatus(statusText);
			}
		});

		feedList = (FeedListView) findViewById(R.id.feedList);
		feedAdapter = new FeedListAdapter(this);
		feedList.setAdapter(feedAdapter);
		feedList.setItemsCanFocus(false);
		feedList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		
		feedList.setOnDataSelectionListener(new OnDataSelectionListener() {
			public void onDataSelected(AdapterView parent, View v,
					int position, long id) {
				FeedItem curItem = (FeedItem) feedAdapter.getItem(position);
				String curText = curItem.getName();
				String curId = curItem.getId();

				Toast.makeText(getApplicationContext(),	"Selected : " + curText, 1000).show();
				
				Intent intent = new Intent(getBaseContext(), HomeActivity.class);
				intent.putExtra("group_id", curId);
				intent.putExtra("my_id", m_id);
				startActivityForResult(intent, 1);

			}

		});
		getUserTimeline();
		startLocationService(); //위치 얻기
		
		groupplus.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent groupplusintent = new Intent(getApplicationContext(),
						GroupPlusWebViewActivity.class);
				startActivity(groupplusintent);
			}
		});
	}
 
	private void updateStatus(String statusText) {
		try {
			String jstr;
			Bundle params = new Bundle();
			ArrayList<String> Message = new ArrayList<String>();
			params.putString("message", loc +statusText);
			Message = feedAdapter.getCheckedIds();
			for (int i = 0; i < Message.size(); i++) {
				facebookvalue.FacebookInstance.request(Message.get(i) + "/feed", params, "POST");
				jstr = facebookvalue.FacebookInstance.request(Message.get(i) + "/feed", params,"POST");
				JSONObject resultObj = Util.parseJson(jstr);
				String feedId = resultObj.getString("id");
				if(locDBTrans.getPermission(m_id).equalsIgnoreCase("o")){
					locDBTrans.setFeedLocation(feedId, StartActivity.latitude.toString(), StartActivity.longitude.toString());
				}
			}

			mInText.setText("");
			Toast.makeText(getApplicationContext(), statusText + " 전송", 1000).show();
		} catch (Exception ex) {
			ex.printStackTrace();
		} catch (FacebookError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getUserTimeline() {
		feedAdapter.clear();
		try {
			Bundle para = new Bundle();
			para.putString("fields", "privacy,name,picture");
			String responseStr = facebookvalue.FacebookInstance.request("me/groups", para);
			feedAdapter.clear();
			JSONObject resultObj = Util.parseJson(responseStr);
			JSONArray jArray = resultObj.getJSONArray("data");
		    for (int i = 0; i < jArray.length(); i++) {
				JSONObject obj = jArray.getJSONObject(i);
				String curPrivacy = obj.getString("privacy");
				if (curPrivacy.equalsIgnoreCase("SECRET") == false)
					continue;
				String curName = obj.getString("name");
				String group_id = obj.getString("id");

				curCount = curCount + group_id + '/';
				FeedItem curItem = new FeedItem(curName, group_id);
				feedAdapter.addItem(curItem);
			}
		    curCount = curCount.substring(0, curCount.length()-1);
		    
		    otherTransfer.setGroupToDB(curCount, m_id, Kumoh_ingActivity.My_gmail, Kumoh_ingActivity.My_phone);
		    
			///////////////////////////////////////////////////////////////////////////////////////////

		    //TODO
		    /*
		     * 데이터베이스의 내용과 실제 그룹에 변화가 있으면 이에해당하는 내용을 데이터베이스에 갱신해야한다.
		     * 아 그럴 필요가 없네..괜히만들었구먼...어차피 갱신함.
		     * 
		     */
		    
		    
		    
		    //파일에 그룹정보를 불러오고 만약 해당정보보다 가입되어있는 그룹의 수가 더 많으면 업데이트하는 부분
		    
		    /*
		    File Userinfo = getDir("Userinfo5", Activity.MODE_PRIVATE);
			String path = Userinfo.getAbsolutePath();
			File file2 = new File(path + "/groupcount.txt");
			try {

				fis = new FileInputStream(file2);
				byte[] data = new byte[fis.available()];
				while (fis.read(data) != -1) {
					;
				}// -1 전체 다읽은거
				fis.close();

				dataCount = new String(data);// String으로 바꿔서 출력해야함. String생성자

			} catch (FileNotFoundException e) {

			} catch (IOException e) {

				// TODO Auto-generated catch block

			}

			if (dataCount.equalsIgnoreCase(curCount) == false) { // 기존의 그룹수와
																	// 비교해서 그룹이
																	// 더 만들어 졌으면

				if (dataCount.length() < curCount.length()) {
					
					StringTokenizer st = new StringTokenizer(curCount, "/");
					StringTokenizer dt = new StringTokenizer(dataCount, "/");
					String curToken = "";
					String dataToken = "";
					while (st.hasMoreTokens()) { // 3

						curToken = st.nextToken();
						while (dt.hasMoreTokens()) {// 2
							dataToken = dt.nextToken();
							if (curToken.equalsIgnoreCase(dataToken)) {
								break;
							}
							if (dt.hasMoreTokens() == false) {
								try {
									
									
									File group = new File(path + "/" + curToken + ".txt");
									try { 
										fos = new FileOutputStream(group);
										String Info = Kumoh_ingActivity.getAppPreferences(this, "facebook_myid") + "$"
												+ Kumoh_ingActivity.My_phone+"$"
												+ Kumoh_ingActivity.My_gmail+ "//";
										fos.write(Info.getBytes());
										
									} catch (Exception e) {
										e.printStackTrace();
									}
									
									
									Bundle params = new Bundle();
									ArrayList<String> Message = new ArrayList<String>();
									params.putString("message", "#%UserInfor="
											+ Kumoh_ingActivity.getAppPreferences(this, "facebook_myid") + "$"
											+ Kumoh_ingActivity.My_phone+"$"
											+ Kumoh_ingActivity.My_gmail+ "//");

									facebookvalue.FacebookInstance.request(
											curToken + "/feed", params, "POST");
								} catch (Exception ex) {
									ex.printStackTrace();
								}
							}
						}

					}

				}

				try {
					fos = new FileOutputStream(file2);
					fos.write(curCount.getBytes());
				} catch (Exception e) {
					e.printStackTrace();
				}

			}*/

			feedAdapter.notifyDataSetChanged();
			// /////////////////////////////////////////////////////////////////////////////////////
		} catch (Exception ex) {
			ex.printStackTrace();
		} catch (FacebookError ext) {
			ext.printStackTrace();
		}
 
	}
	
    private void startLocationService() {

    	// get manager instance
    	LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	 
    	Criteria criteria = new Criteria(); 
    	criteria.setAccuracy(Criteria.ACCURACY_FINE);
    	criteria.setAltitudeRequired(false);
    	criteria.setBearingRequired(false);
    	criteria.setCostAllowed(true);
    	criteria.setPowerRequirement(Criteria.POWER_LOW);
    	String provider = manager.getBestProvider(criteria,true);
    	

    	// set listener
    	GPSListener gpsListener = new GPSListener();
		long minTime = 0;
		float minDistance = 20;

		manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,minTime,minDistance,gpsListener);
		
		// in case of network provider
		manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,minTime,minDistance,gpsListener);

		// get last known location first
		try {
			Location lastLocation = manager.getLastKnownLocation(provider);
			if (lastLocation != null) {
				Double latitude = lastLocation.getLatitude();
				Double longitude = lastLocation.getLongitude();
				locationTransfer.setLocation(m_id, latitude.toString(), longitude.toString());
				// new GeoPoint to be placed on the MapView
				

				loc = " #%UserLocation="+ latitude + "$"+ longitude+"//";
				
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
    }


	private class GPSListener implements LocationListener {

	    public void onLocationChanged(Location location) {
			//capture location data sent by current provider
			latitude = location.getLatitude();
			longitude = location.getLongitude();
			
			try {
					locationTransfer.setLocation(m_id, latitude.toString(), longitude.toString());
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	    

	    public void onProviderDisabled(String provider) {
	    }

	    public void onProviderEnabled(String provider) {
	    }

	    public void onStatusChanged(String provider, int status, Bundle extras) {
	    }

	}
	

	/* 이 쓰레드는 그룹에다가 자신의 정보를 갱신하는데 사용하는듯한데
	 * 만약에 데이터베이스를 사용하면 이부분은 없어도 되는 부분이 아닌가..
	 * 이부분의 목적은 내 사용자 정보를 그룹구성원에게 알려주기 위해서 사용하는것...
	 */
	/*
	class FeedInputThread extends Thread {

		public void run() {
			
			try {
//				File Userinfo = getDir("Userinfo5",	Activity.MODE_PRIVATE); // 파일로 쓰기
//				String path = Userinfo.getAbsolutePath();

				Bundle para = new Bundle();
				para.putString("fields", "privacy,name,picture");
				String responseStr = facebookvalue.FacebookInstance.request("me/groups", para);
				String responseStr2 = facebookvalue.FacebookInstance.request("me");

				JSONObject resultObj2 = Util.parseJson(responseStr2);
				String id = resultObj2.getString("id");

				JSONObject resultObj = Util.parseJson(responseStr);
				JSONArray jArray = resultObj.getJSONArray("data");
				
//				File myInfo = new File(path + "/mine.txt");	//내 정보 저장 파일
				
//				fos = new FileOutputStream(myInfo);
				Info =  id+ "$" + Kumoh_ingActivity.My_phone + "$" + Kumoh_ingActivity.My_gmail + "//";
//				fos.write(Info.getBytes());
					
				for (int i = 0; i < jArray.length(); i++) {		
					
					JSONObject obj = jArray.getJSONObject(i);
					String curPrivacy = obj.getString("privacy");
					if (curPrivacy.equalsIgnoreCase("SECRET") == false)
						continue;
					String curName = obj.getString("name");
					String group_id = obj.getString("id");

					
					groupcount = groupcount + group_id + '/';
					try {
						Bundle params = new Bundle();
						ArrayList<String> Message = new ArrayList<String>();
						params.putString("message", "#%UserInfor=" + id	+ "$" + Kumoh_ingActivity.My_phone + "$" + Kumoh_ingActivity.My_gmail + "//");

						facebookvalue.FacebookInstance.request(group_id + "/feed", params, "POST");

					} catch (Exception ex) {
						ex.printStackTrace();
					}
					
//					File group = new File(path + "/" + group_id + ".txt");
					try {
//						fos = new FileOutputStream(group);
						Info =  id+ "$" + Kumoh_ingActivity.My_phone + "$" + Kumoh_ingActivity.My_gmail + "//";
//						fos.write(Info.getBytes());
						
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
				

			} catch (Exception ex) {
				ex.printStackTrace();
			} catch (FacebookError ext) {
				ext.printStackTrace();
			}
		}
	}*/
}